/**
 * Copyright 2015 - 2016 KeepSafe Software, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.getkeepsafe.relinker.elf;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Function description
 * class Elf32Header
 */
public class Elf32Header extends Elf.Header {
    private final ElfParser mParser;

    /**
     * Constructor Elf32Header
     *
     * @param parser ElfParser
     * @param isBigEndian boolean
     */
    public Elf32Header(final boolean isBigEndian, final ElfParser parser) {
        this.mIsBigEndian = isBigEndian;
        this.mParser = parser;
        final ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.order(isBigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

        type = parser.readHalf(buffer, Constants.TYPE_ID_EIF32_CONSTANT);
        mPhoff = parser.readWord(buffer, Constants.PHOFF_ID_EIF32_CONSTANT);
        mShoff = parser.readWord(buffer, Constants.SHOFF_ID_EIF32_CONSTANT);
        mPhentsize = parser.readHalf(buffer, Constants.PHENTSIZE_ID_EIF32_CONSTANT);
        mPhnum = parser.readHalf(buffer, Constants.PHNUM_ID_EIF32_CONSTANT);
        mShentsize = parser.readHalf(buffer, Constants.SHENTSIZE_ID_EIF32_CONSTANT);
        mShnum = parser.readHalf(buffer, Constants.SHNUM_ID_EIF32_CONSTANT);
        mShstrndx = parser.readHalf(buffer, Constants.SHSTRNDX_ID_EIF32_CONSTANT);
    }

    @Override
    public Elf.SectionHeader getSectionHeader(final int index) throws IOException {
        return new Section32Header(mParser, this, index);
    }

    @Override
    public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {
        return new Program32Header(mParser, this, index);
    }

    @Override
    public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException {
        return new Dynamic32Structure(mParser, this, baseOffset, index);
    }
}
